package com.yfuxdeer.youchat.utils;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.ExternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.yfuxdeer.youchat.activity.UserinfoActivity;

import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.math.BigDecimal;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Random;

public class ImageUtil {

    private static final String TAG = ImageUtil.class.getSimpleName();
    private static Store store = Store.getInstance();
    private static final String URL_PREFIX = "http://139.159.226.207:8034/YouChatServer/head/";
    private static final String URL = "http://139.159.226.207:8034/YouChatServer/upload/";

    private static String getHeadImage(String username, int state) {
        return URL_PREFIX + username + "?v=" + state;
    }

    public static void glideLoad(Context context, String username, int state, ImageView view) {
        Glide.with(context)
                .load(ImageUtil.getHeadImage(username, state))
                .into(view);
    }

    public static void upload(Object caller, String file_path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //建立HTTP连接
                    URL url = new URL(URL);
                    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    //设置提交方式
                    connection.setRequestMethod("POST");
                    //设置提交用户信息
                    connection.addRequestProperty("username", store.getCurrentUser().getUsername());
                    connection.setRequestProperty("content-type", "text/html");

                    //打开输出流 服务器的
                    BufferedOutputStream out = new BufferedOutputStream(connection.getOutputStream());

                    //读取文件上传到服务器
                    FileInputStream fileInputStream = new FileInputStream(new File(file_path));
                    byte[] bytes = new byte[1024];
                    int numReadByte = 0;
                    while ((numReadByte = fileInputStream.read(bytes, 0, 1024)) > 0) {
                        out.write(bytes, 0, numReadByte);
                    }
                    out.flush();
                    fileInputStream.close();
                    //上传
                    new DataInputStream(connection.getInputStream());
                    Log.e(TAG, "run: " + "传完了");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    public static void clearImageAllCache(Context context) {
        Glide.get(context).clearMemory();
        new Thread(new Runnable() {
            @Override
            public void run() {
                Glide.get(context).clearDiskCache();
            }
        }).start();
        String ImageExternalCatchDir = context.getExternalCacheDir() + ExternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR;
        Log.e(TAG, "run: " + ImageExternalCatchDir);
        deleteFolderFile(ImageExternalCatchDir);
    }

    private static void deleteFolderFile(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            try {
                File file = new File(filePath);
                if (file.isDirectory()) {
                    File files[] = file.listFiles();
                    for (File file1 : files) {
                        deleteFolderFile(file1.getAbsolutePath());
                    }
                }
                if (!file.isDirectory()) {
                    file.delete();
                } else {
                    if (file.listFiles().length == 0) {
                        file.delete();
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }

    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public static String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 格式化单位
     *
     * @param size size
     * @return size
     */
    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }
}
